package com.ttmusic.activitys;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import com.ttmusic.application.TTApplication;
import com.ttmusic.core.MusicManager;
import com.ttmusic.core.MusicManager.LoopMode;
import com.ttmusic.dao.MusicInfoDao;
import com.ttmusic.dao.MusicListDao;
import com.ttmusic.entity.AbstractMusic;
import com.ttmusic.entity.AbstractMusic.MusicType;
import com.ttmusic.entity.MusicInfo;
import com.ttmusic.entity.MusicList;
import com.ttmusic.entity.MusiclistMusicinfo;
import com.ttmusic.entity.User;
import com.ttmusic.fragments.maintab.ArtistsFragment;
import com.ttmusic.fragments.maintab.LocalMusicFragment;
import com.ttmusic.fragments.maintab.LyricFragment;
import com.ttmusic.fragments.maintab.MusicListFragment;
import com.ttmusic.fragments.maintab.MusicOfArtistFragment;
import com.ttmusic.fragments.maintab.MusicOfListFragment;
import com.ttmusic.fragments.maintab.SearchOnlineFragment;
import com.ttmusic.utils.BitmapUtil;
import com.ttmusic.utils.MusicUtils;
import com.ttmusic.utils.SharedPreferencesUtil;
import com.ttmusic.utils.Utils;
import com.ttmusic.utils.SQLite.SQLiteUtil;
import com.ttmusic.view.adapters.MusicAdapter;
import com.ttmusic.view.adapters.MusicAdapter.SortType;
import com.ttmusic.view.adapters.MusicListAdapter;
import com.ttmusic.view.listeners.OnScanListener;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends FragmentActivity implements OnCheckedChangeListener, OnClickListener {

	private static RelativeLayout top_ActionBar;
	private static RelativeLayout radiogroupContainer;
  	private static LinearLayout bottom_actionBar;
	
	/**顶部右上角弹出菜单按钮和搜索图标图标**/
	private static ImageView btn_menubar, btn_search;
	/**主界面顶部的单选按钮组**/
	private RadioGroup radioGroup;
	public static RadioButton radio_musiclist, radio_mylove;
	
	/**前一个Fragment 每次切换时都要改变这2个变量**/
	public static Fragment previous;
	/**当前Fragment**/
	public static Fragment current;
	
	
	/**本地音乐fragment  进入app后默认加载这个**/
	public static LocalMusicFragment localMusicFragment;
	/**歌词fragment**/
	public static LyricFragment lyricFragment;
	/**歌手列表fragment**/
	public static ArtistsFragment artistsFragment;
	/**某位歌手的歌曲列表  点击歌手item后要切换的fragment**/
	public static MusicOfArtistFragment musicOfArtistFragment;
	/**歌单列表fragment**/
	public static MusicListFragment musicListFragment;
	/**歌单歌曲列表fragment**/
	public static MusicOfListFragment musicOfListFragment;
	/**在线搜索fragment**/
	public static SearchOnlineFragment searchOnlineFragment;
	
	/**顶部右上角弹出菜单dialog**/
	private Dialog menuBarDialog;
	/**顶部右上角弹出菜单dialog的三个选项**/
	private LinearLayout item_scan_localmusic, item_setting_loopmode, item_setting_sorttype;
	
	/**顶部设置循环模式的弹出菜单**/
	private Dialog loopModeDialog;
	/**设置循环模式的三个选项**/
	private LinearLayout item_loop_list, item_loop_single, item_loop_random;
	
	/**顶部设置排序方式的弹出菜单**/
	private Dialog sortTypeDialog;
	/**设置排序方式的四个选项**/
	private LinearLayout item_sortby_title, item_sortby_artist, item_sortby_album, item_sortby_addtime;
	
	/**扫描本地音乐的进度dialog**/
	private Dialog scannerProgressDialog;
	/**正在扫描的 loading图**/
	private ImageView scanLoading;
	/**已扫描数量**/
	private TextView scanCount;
	private Timer scanTimer;
	
	/**当前展示的歌曲列表的adapter**/
	public static MusicAdapter adapterCurrentShow;
	/**当前播放的歌曲列表的adapter**/
	public static MusicAdapter adapterCurrentPlay;
	
	//-------------------------------音乐播放控制begin-------------------------------
	private MusicInfoDao musicDao;
	/**音乐播放控制管理**/
	public static MusicManager mManager;
	//默认播放列表
  	private List<AbstractMusic> musicInfoList;
	//进度条
	private ProgressBar progressBar;
	//主界面下方的专辑图片
	private ImageView albumImage;
	//主界面下方播放工具栏的歌曲名称、艺术家名称
	private TextView tv_title, tv_artist;
	//主界面下方播放工具栏的播放/暂停按钮  下一首按钮
	private ImageView btn_play_pause, btn_next;
	//改变主界面下方的歌曲名称和艺术家名称
	private Handler bottomActionBarTexthandler;
	//改变主界面下方的进度条的进度
	private Handler bottomProgressHandler;
	private LinearLayout layout_title_artist;
	//定时任务调度器 实现进度条功能
	private Timer timer;
	//主界面下方专辑图片旋转动画
	private Animation circle_anim;
	//-------------------------------音乐播放控制end-------------------------------
	
	//-------------------------------加入歌单功能begin-----------------------------
	//底部操作actionbar
  	private LinearLayout bottom_operation_actionbar, item_new_musiclist;
  	//已选中的歌曲
  	public static List<AbstractMusic> checkedMusicInfos = new ArrayList<AbstractMusic>();
  	//加入歌单dialog
  	private Dialog joinMusicListDialog;
  	private RelativeLayout btn_joinMusicList, btn_removeMusic;
  	private ListView listview_musiclist;
  	private MusicListDao musicListDao;
  	//新建歌单dialog
  	private Dialog newMusicListDialog;
  	//新建歌单的提交按钮和取消按钮
  	private TextView btn_newmusiclist_cancel, btn_newmusiclist_submit;
  	//输入框 歌单名称
  	private EditText new_musiclist_name;
  	//-------------------------------加入歌单功能end-------------------------------
	
	@SuppressLint("HandlerLeak")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//让软键盘覆盖UI界面底部一部分内容
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
		setContentView(R.layout.activity_main);
		timer = new Timer();
		this.musicDao = MusicInfoDao.getInstance();
		this.musicListDao = MusicListDao.getInstance();
		
		btn_search = (ImageView) findViewById(R.id.btn_search);
		btn_search.setOnClickListener(this);
		radiogroupContainer = (RelativeLayout)findViewById(R.id.radiogroupContainer);
		radioGroup = (RadioGroup) findViewById(R.id.radiogroup);
		radioGroup.setOnCheckedChangeListener(this);
		radio_musiclist = (RadioButton)findViewById(R.id.radio_musiclist);
		radio_mylove = (RadioButton)findViewById(R.id.radio_mylove);
		//右上角弹出菜单dialog
		btn_menubar = (ImageView) findViewById(R.id.btn_menubar);
		btn_menubar.setOnClickListener(this);
		
		//初始化顶部右上角弹出菜单dialog
		this.initTopActionMenuBarDialog();
		
		//初始化扫描进度dialog
		this.initScannerProgress();
		
		//初始化循环模式设置dialog
		this.initChangeLoopModeDialog();
		
		//初始化排序方式设置dialog
		this.initSelectSortTypeDialog();
		
		
		
		//音乐播放控制管理
		mManager = MusicManager.getInstance();
		if(null == localMusicFragment) {
			musicInfoList = musicDao.findAll();
			MainActivity.localMusicFragment = new LocalMusicFragment(musicInfoList);
		}
		if(null == MainActivity.lyricFragment) 
			MainActivity.lyricFragment = new LyricFragment();
		top_ActionBar = (RelativeLayout)findViewById(R.id.top_ActionBar);
		bottom_actionBar = (LinearLayout)findViewById(R.id.bottom_actionBar);
		bottom_operation_actionbar = (LinearLayout)findViewById(R.id.bottom_operation_actionbar);
		Utils.go(getSupportFragmentManager(), null, localMusicFragment, R.id.framecontent);
        
        
		//获取当前APP的运行次数  然后运行次数+1
		int runCount = SharedPreferencesUtil.getHasRunCount(this);
		if(runCount == 0) {
			//若是第一次运行APP  自动扫描本地音乐
			this.scan_localmusic();
		}
		SharedPreferencesUtil.setHasRunCount(this, ++runCount);
		
		//自动登录
		boolean isAutoLogin = SharedPreferencesUtil.isAutoLogin(this);
		User user = SharedPreferencesUtil.getCurrentLoginUser(this);
		TTApplication app = (TTApplication)getApplication();
		if(isAutoLogin && app.getUser() == null && user != null) {
			app.setUser(user);
		}
		
		/******每隔1分钟弹出一个有趣的提示语    此功能纯属娱乐******/
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				int i = new Random().nextInt(Utils.friendly.length);
				Toast.makeText(MainActivity.this, Utils.friendly[i], Toast.LENGTH_LONG).show();
			}
		};
		new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
				handler.sendEmptyMessage(0);
			}
		}, 3000, 60000);
		/******每隔1分钟弹出一个有趣的提示语    此功能纯属娱乐******/
		
		
		/********************核心：音乐播放控制**************************/
		//读取前一次退出APP时保存的循环模式
		LoopMode loopMode = SharedPreferencesUtil.getCurrentLoopMode(this);
		mManager.setLoopMode(loopMode);
		
		albumImage = (ImageView)findViewById(R.id.img_album);
		progressBar = (ProgressBar)findViewById(R.id.pro_music);
		if(MusicManager.getNowPlayingSong() != null) {
			progressBar.setMax(MusicManager.getNowPlayingSong().getDuration());
		}
		tv_title = (TextView)findViewById(R.id.tv_title);
		tv_artist = (TextView)findViewById(R.id.tv_artist);
		btn_play_pause = (ImageView)findViewById(R.id.btn_play_pause);
		btn_play_pause.setOnClickListener(this);
		btn_next = (ImageView)findViewById(R.id.btn_next);
		btn_next.setOnClickListener(this);
		layout_title_artist = (LinearLayout)findViewById(R.id.layout_title_artist);
		layout_title_artist.setOnClickListener(this);
		
		//提供给MusicManager内部线程调用用handler.sendMessage后自动跨线程改变BottomActionBar
		bottomActionBarTexthandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				updateBottomActionBar();
			}
		};
		mManager.setHandler(bottomActionBarTexthandler);
		
		if(null != MainActivity.mManager && MainActivity.mManager.isPlaying()) {
			btn_play_pause.setImageResource(R.drawable.img_button_playcontrolbar_transparent_pause_normal);
		}
		
		//每50毫秒来改变一次主界面下方进度条的进度
		bottomProgressHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				int played = MainActivity.mManager.getCurrentProgress();
				progressBar.setProgress(played);
			}
		};
		this.autoChangeProgress();
		
		
		//----------------底部弹出actionBar的加入歌单和删除功能---------------
		btn_joinMusicList = (RelativeLayout)findViewById(R.id.btn_joinMusicList);
		btn_removeMusic = (RelativeLayout)findViewById(R.id.btn_removeMusic);
		btn_joinMusicList.setOnClickListener(this);
		btn_removeMusic.setOnClickListener(this);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			/*搜索按钮 在线搜索歌曲 进行下载*/	
			case R.id.btn_search:
				//Toast.makeText(this, "搜索按钮", Toast.LENGTH_SHORT).show();
				if(null == searchOnlineFragment)
					searchOnlineFragment = new SearchOnlineFragment();
				this.setTopAndBottomActionBarVisibility(View.GONE, View.VISIBLE);
				Utils.go(getSupportFragmentManager(), current, searchOnlineFragment, R.id.mainFragmentContainer);
				break;
			/*顶部右上角菜单*/	
			case R.id.btn_menubar:
				menuBarDialog.show();
				break;
			/*扫描本地音乐 添加到本机SQLite中*/	
			case R.id.item_scan_localmusic:
				this.scan_localmusic();
				break;
			/*打开选择排序方式的dialog*/	
			case R.id.item_setting_loopmode:
				menuBarDialog.dismiss();
				loopModeDialog.show();
				break;
			/*打开设置循环模式的dialog*/
			case R.id.item_setting_sorttype:
				menuBarDialog.dismiss();
				sortTypeDialog.show();
				break;
				
				
/**********************以下是设置循环模式**********************/
			case R.id.item_loop_mode_list:
				item_loop_list.setBackgroundColor(Color.parseColor("#9C27B0"));
				item_loop_single.setBackgroundColor(Color.BLACK);
				item_loop_random.setBackgroundColor(Color.BLACK);
				MainActivity.mManager.setLoopMode(LoopMode.LOOP_LIST);
				this.dismissDialog(loopModeDialog, 200);
				break;
			case R.id.item_loop_mode_single:
				item_loop_single.setBackgroundColor(Color.parseColor("#9C27B0"));
				item_loop_list.setBackgroundColor(Color.BLACK);
				item_loop_random.setBackgroundColor(Color.BLACK);
				MainActivity.mManager.setLoopMode(LoopMode.LOOP_SINGLE);
				this.dismissDialog(loopModeDialog, 200);
				break;
			case R.id.item_loop_mode_random:
				item_loop_random.setBackgroundColor(Color.parseColor("#9C27B0"));
				item_loop_list.setBackgroundColor(Color.BLACK);
				item_loop_single.setBackgroundColor(Color.BLACK);
				MainActivity.mManager.setLoopMode(LoopMode.LOOP_RANDOM);
				this.dismissDialog(loopModeDialog, 200);
				break;
				
				
/**********************以下是设置排序方式*********************/
			case R.id.item_sortby_addtime:	//按添加时间排序
				item_sortby_addtime.setBackgroundColor(Color.parseColor("#9C27B0"));
			    item_sortby_title.setBackgroundColor(Color.BLACK);
			    item_sortby_artist.setBackgroundColor(Color.BLACK);
			    item_sortby_album.setBackgroundColor(Color.BLACK);
				this.dismissDialog(sortTypeDialog, 200);
				if(MusicAdapter.getSortType() != SortType.SORT_BY_ADDTIME) {
					MusicAdapter.setSortType(SortType.SORT_BY_ADDTIME);
					MainActivity.adapterCurrentShow.changeSortType();//重新展示
				}
			    break;
			case R.id.item_sortby_title:	//按歌曲名排序
				item_sortby_addtime.setBackgroundColor(Color.BLACK);
			    item_sortby_title.setBackgroundColor(Color.parseColor("#9C27B0"));
			    item_sortby_artist.setBackgroundColor(Color.BLACK);
			    item_sortby_album.setBackgroundColor(Color.BLACK);
				this.dismissDialog(sortTypeDialog, 200);
				if(MusicAdapter.getSortType() != SortType.SORT_BY_TITLE) {
					MusicAdapter.setSortType(SortType.SORT_BY_TITLE);
					MainActivity.adapterCurrentShow.changeSortType();//重新展示
				}
			    break;
			case R.id.item_sortby_artist:	//按歌手名排序
				item_sortby_addtime.setBackgroundColor(Color.BLACK);
			    item_sortby_title.setBackgroundColor(Color.BLACK);
			    item_sortby_artist.setBackgroundColor(Color.parseColor("#9C27B0"));
			    item_sortby_album.setBackgroundColor(Color.BLACK);
				this.dismissDialog(sortTypeDialog, 200);
				if(MusicAdapter.getSortType() != SortType.SORT_BY_ARTIST) {
					MusicAdapter.setSortType(SortType.SORT_BY_ARTIST);
					MainActivity.adapterCurrentShow.changeSortType();//重新展示
				}
			    break;
			case R.id.item_sortby_album:	//按专辑名排序
				item_sortby_addtime.setBackgroundColor(Color.BLACK);
			    item_sortby_title.setBackgroundColor(Color.BLACK);
			    item_sortby_artist.setBackgroundColor(Color.BLACK);
			    item_sortby_album.setBackgroundColor(Color.parseColor("#9C27B0"));
				this.dismissDialog(sortTypeDialog, 200);
				if(MusicAdapter.getSortType() != SortType.SORT_BY_ALBUM) {
					MusicAdapter.setSortType(SortType.SORT_BY_ALBUM);
					MainActivity.adapterCurrentShow.changeSortType();//重新展示
				}
			    break;
			    
			    
/**********************以下是音乐播放控制********************/
			case R.id.btn_play_pause:
				if(MainActivity.mManager.isPlaying()) {
					//播放中   就暂停并记录播放进度 更改图标为播放按钮
					btn_play_pause.setImageResource(R.drawable.img_button_playcontrolbar_transparent_play_normal);
					MainActivity.mManager.pause();
					if (circle_anim != null) { 
						albumImage.clearAnimation();  //暂停动画  
					}
				}else {
					if(MusicManager.getNowPlayingIndex() >= 0) {
						//暂停中   就恢复播放 更改图标为暂停按钮
						btn_play_pause.setImageResource(R.drawable.img_button_playcontrolbar_transparent_pause_normal);
						MainActivity.mManager.playAfterPause();
						if (circle_anim != null) {  
							albumImage.startAnimation(circle_anim);  //开始动画  
						}
					}
				}
				break;
			case R.id.btn_next:
				if(MusicManager.getPlayingList() != null) {
					MainActivity.mManager.nextSong(true);
				}
				btn_play_pause.setImageResource(R.drawable.img_button_playcontrolbar_transparent_pause_normal);
				this.updateBottomActionBar();
				break;
			case R.id.img_album: //下方图片
			case R.id.layout_title_artist://切换到歌词界面
				timer.purge();
				//正在播放的歌曲不为null 才能切换到歌词界面
				if(null != MusicManager.getNowPlayingSong()) {
					if (circle_anim != null) { 
						albumImage.clearAnimation();  //暂停动画  
					}
					Utils.go(this.getSupportFragmentManager(), MainActivity.current, MainActivity.lyricFragment, R.id.mainFragmentContainer);
				}
				break;
				
				
/**********************以下是多选后的操作功能********************/				
			case R.id.btn_joinMusicList://加入歌单
				if(checkedMusicInfos.size() > 0) {
					this.initJoinMusicListDialog();
					this.joinMusicListDialog.show();
				}else {
					Toast.makeText(this, "您还未选中歌曲", Toast.LENGTH_SHORT).show();
				}
				break;
			case R.id.btn_removeMusic://删除所选歌曲
				break;
			case R.id.item_new_musiclist://新建歌单
				this.initNewMusicListDialog();
				newMusicListDialog.show();
				break;
			case R.id.btn_newmusiclist_cancel://新建歌单-取消
				new_musiclist_name.setText("");
				newMusicListDialog.dismiss();
				break;
			case R.id.btn_newmusiclist_submit://新建歌单-提交
				String listName = new_musiclist_name.getText().toString();
				if(musicListDao.loadByName(listName) != null) {
					Toast.makeText(this, "换个名字吧", Toast.LENGTH_SHORT).show();
				}else {
					MusicList ml = new MusicList(listName, checkedMusicInfos.size(), null, new Date().getTime());
					long listId = musicListDao.save(ml);
					ml.setListId((int)listId);
					for(int i=0;i<checkedMusicInfos.size();i++) {
						musicListDao.saveMusiclistMusicinfo(new MusiclistMusicinfo((int)listId, ((MusicInfo)checkedMusicInfos.get(i)).getSongId().intValue()));
					}
					//切换到“歌单”fragment 
					if(null == musicListFragment) {
						musicListFragment = new MusicListFragment(MainActivity.this);
					}else {
						if(null == MainActivity.musicOfListFragment)
							MainActivity.musicOfListFragment = new MusicOfListFragment(this, ml);
						else
							MainActivity.musicOfListFragment.setMusicList(ml);
					}
					radio_musiclist.setChecked(true);
					Utils.go(getSupportFragmentManager(), current, musicListFragment, R.id.framecontent);
					new_musiclist_name.setText("");
					joinMusicListDialog.dismiss();
					newMusicListDialog.dismiss();
				}
				break;
			default:
				break;
		}
	}
	
	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		switch (checkedId) {
			case R.id.radio_music://歌曲
				Utils.go(getSupportFragmentManager(), current, localMusicFragment, R.id.framecontent);
				break;
			case R.id.radio_artist://艺术家
				if(artistsFragment == null)
					artistsFragment = new ArtistsFragment();
				Utils.go(getSupportFragmentManager(), current, artistsFragment, R.id.framecontent);
				break;
			case R.id.radio_mylove://我的最爱
				MusicList musicList = musicListDao.loadByName("我的最爱");
				//切换到“我的最爱”fragment
				if(null == musicOfListFragment)
					musicOfListFragment = new MusicOfListFragment(MainActivity.this, musicList);
				else
					musicOfListFragment.setMusicList(musicList);
				if(MusicOfListFragment.isCreated) musicOfListFragment.onHiddenChanged(false);
				Utils.go(getSupportFragmentManager(), current, musicOfListFragment, R.id.framecontent);
				break;
			case R.id.radio_musiclist://歌单
				if(null == musicListFragment)
					musicListFragment = new MusicListFragment(MainActivity.this);
				Utils.go(getSupportFragmentManager(), current, musicListFragment, R.id.framecontent);
				break;
			default:
				break;
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		//重置返回键功能
		if (keyCode == KeyEvent.KEYCODE_BACK) {  
			if(current == localMusicFragment || current == artistsFragment || current == musicListFragment) {
				//若当前是localMusicFragment、artistsFragment、musicListFragment就将app移到后台运行 不销毁
				moveTaskToBack(false);  
				return true;
			}
			if(previous == localMusicFragment || previous == artistsFragment || previous == musicListFragment) {
				Utils.go(this.getSupportFragmentManager(), current, previous, R.id.framecontent);
	            return true;  
			}
			Utils.go(this.getSupportFragmentManager(), current, previous, R.id.mainFragmentContainer);
            return true;  
        }  
        return super.onKeyDown(keyCode, event);
	}
	
	
	
	
	/**
	 * 初始化顶部右上角的弹出菜单dialog
	 */
	private void initTopActionMenuBarDialog() {
		menuBarDialog = new Dialog(MainActivity.this, R.style.dialog_noborder);
	    View view = LayoutInflater.from(this).inflate(R.layout.dialog_top_menubar, null);
	    item_scan_localmusic = (LinearLayout)view.findViewById(R.id.item_scan_localmusic);
    	item_setting_loopmode = (LinearLayout)view.findViewById(R.id.item_setting_loopmode);
    	item_setting_sorttype = (LinearLayout)view.findViewById(R.id.item_setting_sorttype);
    	item_scan_localmusic.setOnClickListener(this);
    	item_setting_loopmode.setOnClickListener(this);
    	item_setting_sorttype.setOnClickListener(this);
    	Window dialogWindow = menuBarDialog.getWindow();
    	WindowManager.LayoutParams lp = dialogWindow.getAttributes(); // 获取对话框当前的参数值
    	//lp.x = 0; // 新位置X坐标  
        lp.y = 180; // 新位置Y坐标  
        lp.gravity = Gravity.TOP | Gravity.END; //右上角
        dialogWindow.setAttributes(lp);
    	menuBarDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    	menuBarDialog.setContentView(view);
	}
	
	/**
	 * 初始化设置循环模式的dialog
	 */
	private void initChangeLoopModeDialog() {
	    loopModeDialog = new Dialog(MainActivity.this, R.style.dialog_noborder);
	    View view = LayoutInflater.from(this).inflate(R.layout.dialog_set_loopmode, null);
	    item_loop_list = (LinearLayout)view.findViewById(R.id.item_loop_mode_list);
    	item_loop_single = (LinearLayout)view.findViewById(R.id.item_loop_mode_single);
    	item_loop_random = (LinearLayout)view.findViewById(R.id.item_loop_mode_random);
    	item_loop_list.setOnClickListener(this);
    	item_loop_single.setOnClickListener(this);
    	item_loop_random.setOnClickListener(this);
    	loopModeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
	    loopModeDialog.setContentView(view);
	    //设置显示监听器
	    loopModeDialog.setOnShowListener(new DialogInterface.OnShowListener() {
			@Override
			public void onShow(DialogInterface dialog) {
				if(MainActivity.mManager.getLoopMode() == LoopMode.LOOP_LIST) {
			    	item_loop_list.setBackgroundColor(Color.parseColor("#9C27B0"));
			    }else if(MainActivity.mManager.getLoopMode() == LoopMode.LOOP_SINGLE) {
			    	item_loop_single.setBackgroundColor(Color.parseColor("#9C27B0"));
			    }else if(MainActivity.mManager.getLoopMode() == LoopMode.LOOP_RANDOM) {
			    	item_loop_random.setBackgroundColor(Color.parseColor("#9C27B0"));
			    }
			}
		});
	}
	
	/**
	 * 初始化选择排序方式的dialog
	 */
	private void initSelectSortTypeDialog() {
		sortTypeDialog = new Dialog(MainActivity.this, R.style.dialog_noborder);
	    View view = LayoutInflater.from(this).inflate(R.layout.dialog_set_sorttype, null);
	    item_sortby_addtime = (LinearLayout)view.findViewById(R.id.item_sortby_addtime);
	    item_sortby_title = (LinearLayout)view.findViewById(R.id.item_sortby_title);
	    item_sortby_artist = (LinearLayout)view.findViewById(R.id.item_sortby_artist);
	    item_sortby_album = (LinearLayout)view.findViewById(R.id.item_sortby_album);
	    item_sortby_addtime.setOnClickListener(this);
	    item_sortby_title.setOnClickListener(this);
	    item_sortby_artist.setOnClickListener(this);
	    item_sortby_album.setOnClickListener(this);
	    sortTypeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
	    sortTypeDialog.setContentView(view);
	    //设置显示监听器
	    sortTypeDialog.setOnShowListener(new DialogInterface.OnShowListener() {
			@Override
			public void onShow(DialogInterface dialog) {
				if(MusicAdapter.getSortType() == SortType.SORT_BY_ADDTIME) {
					item_sortby_addtime.setBackgroundColor(Color.parseColor("#9C27B0"));
			    }else if(MusicAdapter.getSortType() == SortType.SORT_BY_TITLE) {
			    	item_sortby_title.setBackgroundColor(Color.parseColor("#9C27B0"));
			    }else if(MusicAdapter.getSortType() == SortType.SORT_BY_ARTIST) {
			    	item_sortby_artist.setBackgroundColor(Color.parseColor("#9C27B0"));
			    }else if(MusicAdapter.getSortType() == SortType.SORT_BY_ALBUM) {
			    	item_sortby_album.setBackgroundColor(Color.parseColor("#9C27B0"));
			    }
			}
		});
	}
	
	/**
	 * 200毫秒后隐藏dialog
	 */
	private void dismissDialog(final Dialog dialog, long delayMillis) {
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				dialog.dismiss();
			}
		}, delayMillis);
	}

	/**
	 * 退出APP时记录当前的循环模式信息
	 */
	@Override
	protected void onDestroy() {
		//保存当前循环模式
		SharedPreferencesUtil.setCurrentLoopMode(this, mManager.getLoopMode());
		//关闭本app所连接的数据库
		SQLiteUtil.close();
		super.onDestroy();
	}
	
	/**
	 * 设置顶部和底部的actionBar是否可见
	 * @param visibility
	 */
	public void setTopAndBottomActionBarVisibility(int visibility_top, int visibility_bottom) {
		//隐藏或显示顶部的top_ActionBar
		top_ActionBar.setVisibility(visibility_top);
		//隐藏或显示顶部的radiogroup
		radiogroupContainer.setVisibility(visibility_top);
		
		//隐藏或显示底部的bottom_ActionBar
		bottom_actionBar.setVisibility(visibility_bottom);
		if(visibility_bottom == View.VISIBLE) {
			mManager.setHandler(bottomActionBarTexthandler);
			mManager.updateBottomActionBar();
		}
	}
	
	
	
	
	//---------------------------------以下是音乐播放控制功能-------------------------------
	/**
     * 每50毫秒自动改变主界面进度条的进度
     */
    private void autoChangeProgress() {
    	timer.schedule(new TimerTask() {
            @Override  
            public void run() {  
                if(MusicManager.isAllowProgressBarChanging){  
                	bottomProgressHandler.sendMessage(new Message());
                }  
            }
		}, 0, 50);
    }
    /**
	 * 更新底部BottomActionBar的歌曲名称和艺术家名称
	 */
	public void updateBottomActionBar() {
		Bitmap bitmap = null;
		if(MusicManager.getNowPlayingSong() != null) {
			tv_title.setText(MusicManager.getNowPlayingSong().getTitle());
	        tv_artist.setText(MusicManager.getNowPlayingSong().getArtist());
	        progressBar.setMax(MusicManager.getNowPlayingSong().getDuration());
	        adapterCurrentPlay.notifyDataSetChanged();
	        if(MainActivity.mManager.isPlaying()) {
	        	btn_play_pause.setImageResource(R.drawable.img_button_playcontrolbar_transparent_pause_normal);
	        }else {
	        	btn_play_pause.setImageResource(R.drawable.img_button_playcontrolbar_transparent_play_normal);
	        }
			if(MusicManager.getNowPlayingSong().getType() == MusicType.Online) {
				//bitmap = BitmapFactory.dec
				bitmap = BitmapUtil.getMusicImg(this, null);
			}else {
				bitmap = BitmapUtil.getMusicImg(this, MusicManager.getNowPlayingSong().getPath());
			}
		}else {
			bitmap = BitmapUtil.getMusicImg(this, null);
		}
		albumImage.setImageBitmap(bitmap);
		
		//旋转
		if (circle_anim == null) { 
			circle_anim = AnimationUtils.loadAnimation(this, R.anim.anim_round_rotate);  
			LinearInterpolator interpolator = new LinearInterpolator();  //设置匀速旋转，在xml文件中设置会出现卡顿  
			circle_anim.setInterpolator(interpolator);  
		}
		albumImage.startAnimation(circle_anim);  //开始动画  
	}
	/**
	 * APP从后台切换到前台运行，界面恢复
	 */
	@Override
	public void onResume() {
		if(MainActivity.mManager.isPlaying()) {
        	btn_play_pause.setImageResource(R.drawable.img_button_playcontrolbar_transparent_pause_normal);
        }else {
        	btn_play_pause.setImageResource(R.drawable.img_button_playcontrolbar_transparent_play_normal);
        }
		super.onResume();
	}
	
	
	
	
	
	
	
	
	
	
	//---------------------------------以下是扫描本地音乐的功能实现---------------------------
	/**
	 * 初始化扫描进度dialog
	 */
	private void initScannerProgress() {
		scannerProgressDialog = new Dialog(MainActivity.this, R.style.dialog_noborder);
	    View view = LayoutInflater.from(this).inflate(R.layout.dialog_scan_progress, null);
	    scanLoading = (ImageView)view.findViewById(R.id.scanLoading);
	    scanCount = (TextView)view.findViewById(R.id.scanCount);
    	scannerProgressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    	scannerProgressDialog.setContentView(view);
    	//设置点击旁边地方时不能关闭它 只有当扫描完成或者扫描失败才关闭它
    	scannerProgressDialog.setCancelable(false);
	}
	private int i = 0;					//控制进度改变
	private int count = 0;				//已扫描数量
	private boolean isLoading = true; 	//是否正在扫描
	/**
	 * 扫描本地音乐到自己创建的表中 TB_ARTIST_INFO TB_ALBUM_INFO TB_MUSIC_INFO
	 */
	public void scan_localmusic() {
		scanTimer = new Timer();
		menuBarDialog.dismiss();
		scannerProgressDialog.show();
		MusicUtils mu = new MusicUtils(this);
		mu.setOnScanListener(new OnScanListener() {
			@Override
			public void onSuccess() {
				isLoading = false;
				scanTimer.purge();
				scanCount.setTextColor(Color.GREEN);
				scanCount.setText("扫描完毕 共" + count + "首");
				dismissDialog(scannerProgressDialog, 800);
				count = 0;
				musicInfoList = musicDao.findAll();
				localMusicFragment.changeData(musicInfoList);
				if(artistsFragment != null)
					artistsFragment.changeData();
				//System.out.println("扫描成功");
			}
			@Override
			public void onScan(MusicInfo musicInfo) {
				scanCount.setText("已扫描" + ++count + "首");
				//System.out.println("正在扫描 " + musicInfo.getSongId() + "~" + musicInfo.getPath());
			}
			@Override
			public void onFail() {
				isLoading = false;
				scanTimer.purge();
				scanCount.setTextColor(Color.RED);
				scanCount.setText("扫描失败 请重试");
				//System.out.println("扫描失败");
			}
		});
		mu.startScan();
		scanTimer.schedule(new TimerTask() {
			@Override
			public void run() {
				scanHandler.sendMessage(scanHandler.obtainMessage());
			}
		}, 0, 100);
	}
	private Handler scanHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if(isLoading) {
				switch (i) {
					case 0:scanLoading.setImageResource(R.drawable.loading_0);break;
					case 1:scanLoading.setImageResource(R.drawable.loading_1);break;
					case 2:scanLoading.setImageResource(R.drawable.loading_2);break;
					case 3:scanLoading.setImageResource(R.drawable.loading_3);break;
					case 4:scanLoading.setImageResource(R.drawable.loading_4);break;
					case 5:scanLoading.setImageResource(R.drawable.loading_5);break;
					case 6:scanLoading.setImageResource(R.drawable.loading_6);break;
					case 7:scanLoading.setImageResource(R.drawable.loading_7);break;
					default:break;
				}
				i++;
				if(i == 7) {i = 0;}
			}
		}
	};
	
	
	//-------------------------以下是歌曲列表界面多选后的操作控制功能-------------------------------
	public void setBottomOperationActionbarVisibility(int visibility) {
		bottom_operation_actionbar.setVisibility(visibility);
	}
	/**
	 * 初始化加入歌单dialog
	 */
	private void initJoinMusicListDialog() {
		joinMusicListDialog = new Dialog(MainActivity.this, R.style.dialog_noborder);
	    View view = LayoutInflater.from(this).inflate(R.layout.dialog_joinmusiclist, null);
	    item_new_musiclist  = (LinearLayout)view.findViewById(R.id.item_new_musiclist);
	    item_new_musiclist.setOnClickListener(this);
		listview_musiclist = (ListView)view.findViewById(R.id.listview_musiclist);
		final List<MusicList> musicLists = musicListDao.findAll();
		MusicListAdapter mla = new MusicListAdapter(this, musicLists, false);
		listview_musiclist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long index) {
				//加入歌单 
				MusicList ml = musicLists.get((int)index);
				MusiclistMusicinfo mm = null;
				for(int i=0;i<checkedMusicInfos.size();i++) {
					//先判断当前歌单里面是否已经包含所选歌曲
					mm = musicListDao.loadMusiclistMusicinfoByListIdAndSongId(ml.getListId(), ((MusicInfo)checkedMusicInfos.get(i)).getSongId());
					if(mm == null) {
						musicListDao.saveMusiclistMusicinfo(new MusiclistMusicinfo(ml.getListId(), ((MusicInfo)checkedMusicInfos.get(i)).getSongId().intValue()));
						//更改歌单的歌曲数量
						ml.setNumSongs(ml.getNumSongs() + 1);
					}
				}
				musicListDao.update(ml);
				if("我的最爱".equals(ml.getListName())) {
					//切换到“我的最爱”fragment
					if(null == musicOfListFragment)
						musicOfListFragment = new MusicOfListFragment(MainActivity.this, ml);
					else
						musicOfListFragment.setMusicList(ml);
					radio_mylove.setChecked(true);
					Utils.go(getSupportFragmentManager(), current, musicOfListFragment, R.id.framecontent);
				}else {
					//切换到“歌单”fragment 
					if(null == musicListFragment)
						musicListFragment = new MusicListFragment(MainActivity.this);
					radio_musiclist.setChecked(true);
					Utils.go(getSupportFragmentManager(), current, musicListFragment, R.id.framecontent);
				}
				dismissDialog(joinMusicListDialog, 200);
			}
		});
		listview_musiclist.setAdapter(mla);
	    joinMusicListDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
	    joinMusicListDialog.setContentView(view);
	}
	
	/**
	 * 初始化新建歌单dialog
	 */
	private void initNewMusicListDialog() {
		newMusicListDialog = new Dialog(MainActivity.this, R.style.dialog_noborder);
	    View view = LayoutInflater.from(this).inflate(R.layout.dialog_new_musiclist, null);
	    btn_newmusiclist_cancel = (TextView)view.findViewById(R.id.btn_newmusiclist_cancel);
	    btn_newmusiclist_submit = (TextView)view.findViewById(R.id.btn_newmusiclist_submit);
	    btn_newmusiclist_cancel.setOnClickListener(this);
	    btn_newmusiclist_submit.setOnClickListener(this);
	    new_musiclist_name = (EditText)view.findViewById(R.id.new_musiclist_name);
	    newMusicListDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
	    newMusicListDialog.setContentView(view);
	    newMusicListDialog.setCancelable(false);
	}
	
}
